<template>
  <a-popover
    placement="bottomRight"
    trigger="click"
    :open="open"
    @openChange="handleOpenChange"
  >
    <template #content>
      <div class="notification-list">
        <a-list :data-source="requests" :loading="loading">
          <template #renderItem="{ item }">
            <a-list-item>
              <div class="request-item">
                <a-avatar :src="item.senderAvatar" />
                <div class="request-info">
                  <div class="sender-name">{{ item.senderName }}</div>
                  <div class="apply-reason">{{ item.applyReason }}</div>
                </div>
                <div class="request-actions">
                  <a-button
                    type="primary"
                    size="small"
                    @click="handleRequest(item.id, true)"
                  >
                    同意
                  </a-button>
                  <a-button size="small" @click="handleRequest(item.id, false)">
                    拒绝
                  </a-button>
                </div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </template>

    <a-badge :count="unreadCount">
      <bell-outlined />
    </a-badge>
  </a-popover>
</template>

<script setup lang="ts">
declare global {
  interface WindowEventMap {
    "websocket-message": CustomEvent;
  }
}

import { ref, onMounted, onUnmounted } from "vue";
import { BellOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { useAuthStore } from "@/store/auth";
import { getPendingRequests, handleFriendRequest } from "@/api/contact";

const authStore = useAuthStore();
const requests = ref([]);
const loading = ref(false);
const open = ref(false);
const unreadCount = ref(0);

const loadRequests = async () => {
  loading.value = true;
  try {
    if (!authStore.user?.id) return;
    const response = await getPendingRequests(authStore.user.id);
    if (response.data.code === 200) {
      requests.value = response.data.data;
      unreadCount.value = requests.value.length;
    }
  } catch (error) {
    message.error("加载好友请求失败");
  } finally {
    loading.value = false;
  }
};

const handleRequest = async (requestId: number, accept: boolean) => {
  try {
    if (!authStore.user?.id) return;
    const response = await handleFriendRequest(
      authStore.user.id,
      requestId,
      accept
    );
    if (response.data.code === 200) {
      message.success(accept ? "已添加好友" : "已拒绝请求");
      loadRequests(); // 重新加载请求列表
    }
  } catch (error) {
    message.error("处理好友请求失败");
  }
};

const handleOpenChange = (visible: boolean) => {
  open.value = visible;
  if (visible) {
    loadRequests();
  }
};
// 监听WebSocket消息
type WebSocketMessageEvent = CustomEvent<any>;

const handleWebSocketMessage = (event: WebSocketMessageEvent) => {
  const data = event.detail;
  if (data.type === "NEW_FRIEND_REQUEST") {
    console.log("收到新的好友请求", data);
    unreadCount.value++;
    loadRequests();
  }
};

onMounted(() => {
  loadRequests();
  // 添加WebSocket消息监听
  window.addEventListener("websocket-message", handleWebSocketMessage);
});

onUnmounted(() => {
  window.removeEventListener("websocket-message", handleWebSocketMessage);
});
</script>

<style scoped>
.notification-list {
  width: 300px;
  max-height: 400px;
  overflow-y: auto;
}

.request-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.request-info {
  flex: 1;
}

.sender-name {
  font-weight: 500;
}

.apply-reason {
  font-size: 12px;
  color: #666;
}

.request-actions {
  display: flex;
  gap: 8px;
}
</style>
